// pages/order/order.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    address: '',
    isCheck: true,
    orderInfo: ''
  },

  defaultAddress() {
    wx.$https('address.default.selected').then(res => {
      this.setData({
        address: res || ''
      })
    })
  },

  chooseCoupon(e) {
    wx.$nav('/pages/coupon/coupon', {
      list: JSON.stringify(this.data.coupon),
      shopId: e.currentTarget.dataset.id,
      currentCouponId: e.currentTarget.dataset.cid,
      sum: e.currentTarget.dataset.sum
    })
  },

  ordersAdd() {
    let goodsInfo = ''
    let skuDetail = this.data.skuDetail
    let list = this.data.productList
    let spcartItemsIds = ''
    for (let x in list) {
      for (let y in list[x].items) {
        goodsInfo += `${goodsInfo == '' ? '' : ','}${list[x].items[y].goodsSkuId}|${list[x].items[y].num}${list[x].coupon?('|'+list[x].coupon.accountCouponId):''}`
        spcartItemsIds += `${spcartItemsIds == '' ? '' : ','}${list[x].items[y].spcartItemsId}`
      }
    }
    wx.$https('orders.add', {
      addressId: this.data.address.addressId,
      goodsInfo: goodsInfo,
      spcartItemsIds: spcartItemsIds
    }).then(res => {
      wx.$unifiedorder(res.ordersIds, function () {
        wx.redirectTo({
          url: '/pages/orderList/orderList?status=2&orderId=' + res.ordersIds
        });
      }, function () {
        wx.redirectTo({
          url: '/pages/orderList/orderList?status=0&orderId=' + res.ordersIds
        });
      })
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this
    let productList = JSON.parse(options.productList);
    for (let x in productList) {
      productList[x].sum = 0
      for (let y in productList[x].items) {
        productList[x].sum += productList[x].items[y].num * productList[x].items[y].price
      }
      productList[x].sum = productList[x].sum.toFixed(2)
    }
    this.setData({
      productList: productList
    })
    //注释部分为用微信默认地址系统
    // let address = wx.getStorageSync('address')
    // that.setData({
    //   address: address
    // })
    // wx.getSetting({
    //   success(res) {
    //     if (res.authSetting['scope.address'] == true) {
    //       that.setData({
    //         scopeAddress: true
    //       })
    //     }
    //   }
    // })
  },

  allSum() { //计算合计
    let list = this.data.productList
    let sum = 0
    for (let x in list) {
      sum += Number(list[x].subtotal)
    }
    this.setData({
      sum: sum.toFixed(2)
    })
  },

  getCoupon() {
    let list = this.data.productList
    let couponInfo = ''
    for (let x in list) {
      couponInfo += `${couponInfo==''?'':','}${list[x].shopId}|${list[x].sum}`
    }
    wx.$https('orders.coupon.list', {
      couponInfo: couponInfo
    }).then(res => {
      this.setData({
        coupon: wx.$coupon(res)
      })
      this.DefaultCoupon()
    })
  },

  DefaultCoupon() {
    let coupon = this.data.coupon
    if (!coupon) { //如果优惠券列表为空 不进行操作
      this.calcSum()
      return
    }
    coupon = coupon.map(x => { //给每个优惠券添加当前未使用标记
      x.isUse = false
      return x
    })
    let list = this.data.productList
    list.map(i => {
      i.coupons = coupon.filter(v => { //筛选出属于自己店铺专属优惠券
        return i.shopId == v.shopId && i.sum - v.thresholdPrice >= 0 //金额筛选，商品金额必须大于等于优惠券生效额度
      })
      i.coupons.sort((a, b) => { //对每个店铺优惠券进行降序排序
        return b.price - a.price
      })
      if (i.coupons && i.coupons.length != 0) { //如果店铺优惠券列表不为空，默认优惠券
        for (let x = 0; x < i.coupons.length; x++) {
          if (i.sum - i.coupons[x].thresholdPrice >= 0) {
            i.coupon = i.coupons[x]
            i.coupons[x].isUse = true
            i.coupons.unshift(i.coupons.splice(x, 1)[0])
            break
          }
        }
      }
      return i
    })
    let common = coupon.filter(i => { //筛选出平台通用优惠券
      return !i.shopId || i.shopId == '0'
    })
    common.sort((a, b) => { //对平台通用优惠券降序排序
      return b.price - a.price
    })
    //将店铺分为有优惠券的和没优惠券的
    let noCoupon = list.filter(v => {
      return !v.coupon
    })
    let haveCoupon = list.filter(v => {
      return v.coupon
    })
    haveCoupon.sort((a, b) => { //将有优惠券的由小到大排序
      return a.coupon.price - b.coupon.price
    })
    for (let x = 0; x < common.length; x++) { //将所有没券的填上
      for (let y = 0; y < noCoupon.length; y++) {
        if (noCoupon[y].sum > common[x].thresholdPrice) {
          noCoupon[y].coupon = common[x]
          common[x].isUse = true
          break
        }
      }
    }
    for (let x = 0; x < common.length; x++) { //给已使用自己最大优惠券的店铺 分配额度更大的 满足条件的平台通用券
      for (let y = 0; y < haveCoupon.length; y++) {
        if (common[x].price - haveCoupon[y].coupon.price > 0 && haveCoupon[y].sum - common[x].thresholdPrice > 0) { //当前遍历的平台优惠券金额 大于店铺自己的最大优惠券。且店铺消费金额满足优惠券最低额度
          haveCoupon[y].coupon = common[x]
          common[x].isUse = true
          haveCoupon[y].coupons[0].isUse = false
        }
      }
    }
    // for (let i = 0; i < common.length; i++) {
    //   let np = ''
    //   let isUse = false
    //   for (let n in list) { //寻找最小优惠券，准备将之替换为大额通用 bug
    //     if (!list[n].coupon) { //先寻找没有优惠券的店铺
    //       list[n].coupon = common[i]
    //       common[i].isUse = true
    //       isUse = true
    //       break
    //     }
    //     if (np == '' || np.price > list[n].coupon.price) { //再寻找当前最小优惠券
    //       np = {
    //         price: list[n].coupon.price,
    //         n: n
    //       }
    //     }
    //   }
    //   if (!isUse && list[np.n].coupon.price < common[i].price) {
    //     list[np.n].coupon = common[i]
    //     common[i].isUse = true
    //   }
    // }
    list = haveCoupon.concat(noCoupon)
    this.setData({
      productList: list,
      coupon: coupon
    })
    this.calcSum()
  },


  setCoupon(coupon, shopId, currentCouponId) {
    let list = this.data.productList
    let cList = this.data.coupon
    for (let x in list) {
      if (list[x].shopId == shopId)
        list[x].coupon = coupon
    }
    for (let x in cList) {
      if (currentCouponId == cList[x].accountCouponId) {
        cList[x].isUse = false
      }
      if (coupon.accountCouponId == cList[x].accountCouponId) {
        cList[x].isUse = true
      }
    }
    this.setData({
      productList: list,
      coupon: cList
    })
    this.calcSum()
  },


  calcSum() { //计算小计
    let list = this.data.productList
    for (let x in list) {
      let coupon = list[x].coupon
      if (!coupon) {
        list[x].subtotal = list[x].sum
      } else {
        list[x].subtotal = (list[x].sum - coupon.price).toFixed(2)
      }
    }
    this.setData({
      productList: list
    })
    this.allSum()
  },

  //onload之后的方法 为用微信默认地址系统的方法
  getAddress() {
    wx.$nav('/pages/addressList/addressList', {
      way: 'from_order'
    })
  },

  getSite() {
    let that = this
    wx.getSetting({
      success(res) {
        if (res.authSetting['scope.address'] == false) {
          wx.showModal({
            title: '获取地址',
            content: '未开启访问地址权限，是否前往开启？',
            success(res) {
              if (!res.cancel) {
                wx.openSetting({
                  success() {
                    that.choAddress()
                  }
                })
              }
            }
          })
        } else {
          that.choAddress()
        }
      }
    })
  },

  choAddress() {
    let that = this
    wx.chooseAddress({
      success: (res) => {
        that.setData({
          address: res
        })
        wx.setStorageSync('address', res)
      },
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (this.data.isCheck) {
      this.defaultAddress()
    } else {
      this.setData({
        isCheck: true
      })
    }
    this.getCoupon()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})